#pragma once

#include <QObject>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QFile>
#include <QTimer>
#include <QElapsedTimer>

class HttpDownloader : public QObject
{
    Q_OBJECT

public:
    explicit HttpDownloader(QObject* parent = nullptr);
    ~HttpDownloader();

    // 下载控制
    void startDownload(const QString& url, const QString& filePath);
    void pauseDownload();
    void resumeDownload();
    void cancelDownload();
    bool isDownloading() const;

    // 获取下载信息
    qint64 getDownloadedSize() const;
    qint64 getTotalSize() const;
    double getProgress() const;
    QString getSpeed() const;

signals:
    void progressChanged(double percentage, qint64 bytesReceived, qint64 bytesTotal);
    void speedUpdated(const QString& speed);
    void statusChanged(const QString& status);
    void finished(bool success, const QString& message);
    void errorOccurred(const QString& error);

private slots:
    void onReadyRead();
    void onDownloadProgress(qint64 bytesReceived, qint64 bytesTotal);
    void onFinished();
    void onError(QNetworkReply::NetworkError code);
    void updateSpeed();

private:
    QNetworkAccessManager* m_manager;
    QNetworkReply* m_reply;
    QFile* m_file;
    QTimer* m_speedTimer;
    QElapsedTimer m_downloadTimer;

    QString m_url;
    QString m_filePath;
    qint64 m_totalSize;
    qint64 m_downloadedSize;
    qint64 m_lastDownloadedSize;
    double m_currentSpeed;
    bool m_isPaused;

    void reset();
    QString formatSpeed(qint64 bytesPerSecond);
    QString formatSize(qint64 bytes);
};